#!/usr/bin/env python
# encoding: utf-8
"""
@Author: Beam
@Mail:506556658@qq.com
@file: index.py
@time: 2017/9/20 22:12
"""

from django.shortcuts import HttpResponse,redirect,render
from basis import authforms
from basis import models
from basis import check_code

def checkcode(request):
	'''生成验证码'''
	import io
	stream = io.BytesIO()
	img,code = check_code.create_validate_code()
	img.save(stream,"png")
	request.session["CheckCode"] = code
	return HttpResponse(stream.getvalue())

def index(request):
	if request.method == 'GET':
		loginform = authforms.LoginForm()
		return render(request,'index.html',{'loginObj':loginform})

	elif request.method == 'POST':
		print(request.POST)
		#result = {'status':True,'message':None,'data':None}
		loginform = authforms.LoginForm(request.POST)
		if loginform.is_valid():
			username = loginform.clean()['username']
			password = loginform.clean()['password']
			obj = models.Users.objects.filter(user=username,passwd=password)
			if obj :
				check_code = request.POST.get('checkCode')
				print('用户输入',check_code.lower())
				print('系统生成',request.session.get('CheckCode'))
				if check_code.lower() == request.session.get('CheckCode').lower():
					return HttpResponse('登录成功')
				else:
					msg = '验证码有误！'
					return render(request, 'index.html', {'loginObj': loginform, 'errMessage': msg})
			else:
				msg = '用户或密码输入错误，请确认！'
				return render(request, 'index.html', {'loginObj': loginform,'errMessage':msg})#,'CheckCode':request.session.get('CheckCode')})
		else:
			print(loginform.errors)
		return render(request, 'index.html', {'loginObj': loginform})